'use strict';

const Controller = require('egg').Controller;
const fs = require('fs')
const pump = require('mz-modules/pump')
class HomeController extends Controller {
  async login(){
    const  {ctx, app}  = this;
    // const token = app.jwt.sign({
    //   username:'admin'
    // },app.config.jwt.secret)
    const result = await ctx.service.user.login(ctx.request.body)
    ctx.body = result
  }
  async index() {
    const  ctx  = this.ctx;
    let str = ctx.request.headers.origin
    const strs = str.slice(str.lastIndexOf('/')+1)
    const result = await ctx.service.public.geti(strs)
    if(result.code === 200){
      const result1 = await ctx.curl('http://api.my9b.com/api.php?t=jnd28');
      ctx.status=result1.status;
      ctx.body = result1.data;
    }else{
      ctx.body = result
    }
  }
  // 测试api
  async demo(){
    const  ctx  = this.ctx;
    ctx.body = ctx.params.httpid
  }
  async upimg(){
    const { ctx } = this;
    const parts = ctx.multipart({ autoFields: true });
    let files = {};
    let stream;
    while ((stream = await parts()) != null) {
      if(!stream.filename){
        break;
      }
      const fieldname = stream.fieldname; // file表单的名字
      // 上传图片的目录
      const dir = await this.service.tools.getUploadFile(stream.filename);
      const target = dir.uploadDir;
      const writeStream = fs.createWriteStream(target);
      await pump(stream, writeStream);
      files = Object.assign(files, {
        [fieldname]: dir.saveDir
      });
    }
  
    if(Object.keys(files).length > 0){
      ctx.body = {
        code: 200,
        message: '图片上传成功',
        data: files
      }
    }else{
      ctx.body = {
        code: 201,
        message: '图片上传失败',
        data: {}
      }
    }
  }
}

module.exports = HomeController;
